package com.exercise.module.common.file.controller;/**
 * Created by kete on 2017-05-11.
 */

import com.exercise.module.common.dao.mapper.SysDocFileMapper;
import com.exercise.module.common.file.service.FileService;
import com.exercise.utils.JsonBean;
import com.exercise.utils.JsonUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 作者：kete
 * 创建时间：2017-05-11 17:15
 * 功能描述：
 * 版本：
 */
@Controller
@RequestMapping("/sys")
public class UploadController {

    @Autowired
    private FileService fileService;

    @Autowired
    public SysDocFileMapper sysDocFileMapper;

    @RequestMapping("/upload")
    @ResponseBody
    public void index(@RequestParam(value = "Filedata", required = false) MultipartFile file, String module1, String module2, String share, String expDate, String action, HttpServletRequest request, HttpServletResponse response) {
        String result = null;

        JsonBean jsonBean = new JsonBean();

        if (StringUtils.isEmpty(module1)) {
            jsonBean.put("status", 0);
            jsonBean.setMessage("模块1不能为空!");
        }

        if (StringUtils.isEmpty(module2)) {
            jsonBean.put("status", 0);
            jsonBean.setMessage("模块2不能为空!");
        }

        if (file == null || file.getSize() <= 0) {
            jsonBean.put("status", 0);
            jsonBean.setMessage("上传文件大小为空!");
        }

        if (StringUtils.isBlank(jsonBean.getMessage())) {
            String fileId = fileService.putFile(file, module1, module2);

            if("uplaodimage".equals(action)) {
                String ext = FilenameUtils.getExtension(file.getName());
                jsonBean.put("state", "SUCCESS");
                jsonBean.put("original", file.getName());
                jsonBean.put("size", file.getSize() + "");
                jsonBean.put("title", fileId + "." + ext);
                jsonBean.put("type", "." + ext);
                jsonBean.put("url", "/sys/download/" + fileId + ".htm");
            } else {
                jsonBean.put("status", 1);
                jsonBean.put("name", file.getName());
                jsonBean.put("url", fileId);
            }
        }

        result = JsonUtils.toJSon(jsonBean);

        try {
            PrintWriter out = response.getWriter();
            out.println(result);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
